<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-alert
        show-icon
        title="注意: 只允许为第三级分类设置相关参数"
        type="warning"
        :closable="false"
      >
      </el-alert>
      <!-- 选择商品区域 -->
      <el-row class="cat_out">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader
            expand-trigger="hover"
            v-model="selectedKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="parenthandleChange"
          >
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tab 页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="AddDialogVisible = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                  closable @close="handleClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- 按钮 -->
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisabled"
            @click="AddDialogVisible = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染tag标签 -->
                <el-tag
                  :key="i"
                  v-for="(item, i) in scope.row.attr_vals"
                  closable @close="handleClose(i,scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入的文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="AddDialogVisible"
      width="50%"
      @close="addDialogclose"
    >
      <!-- 文字信息 -->
      <el-form
        :model="addFrom"
        :rules="addFromRules"
        ref="addFromRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="AddDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addparams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogclose"
    >
      <!-- 文字信息 -->
      <el-form
        :model="editFrom"
        :rules="editFromRules"
        ref="editFromRef"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editFrom.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editparams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类的数据列表
      cateList: [],

      // 指定级联选择器的配置对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
        checkStrictly: true,
      },
      // 选中的父级分类的ID数组
      selectedKeys: [],
      // 被激活页签的名称
      activeName: "many",
      // 动态参数的数据
      manyTableData: [],
      // 静态属性的数据
      onlyTableData: [],
      // 控制添加对话框的显示和影藏
      AddDialogVisible: false,
      // 添加参数的表单数据对象
      addFrom: {
        attr_name: "",
      },
      // 添加表单的校验规则
      addFromRules: {
        attr_name: [
          { required: true, message: "请输出参数名称", trigger: "blur" },
        ],
      },
      // 控制修改对话框的显示颖仓
      editDialogVisible: false,
      // 修改参数的表单数据对象
      editFrom: {
        attr_name: "",
      },
      // 修改表单的校验
      editFromRules: {
        attr_name: [
          { required: true, message: "请输出参数名称", trigger: "blur" },
        ],
      },

    };
  },
  created() {
    this.getCateList();
  },
  mounted() {},
  methods: {
    // 获取所有的商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      }
      this.$message.success("获取商品列表分类成功");
      this.cateList = res.data;
      // console.log(this.cateList);
    },
    // 级联选择框发生改变触发的事件
    parenthandleChange() {
      this.getParamsData();

    },
    // tab标签页点击事件的处理函数
    handleTabClick() {
      console.log(this.activeName);
      this.getParamsData();
    },
    // 获取参数的列表数据
    async getParamsData() {
      // console.log(this.selectedKeys);
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = [];
        // 清空2级菜单选项
        this.manyTableData = []
        this.onlyTableData = []
        return;
      }
      // 证明选中的是3级分类
      console.log(this.selectedKeys);
      // 根据所选中的分类id 和当前所处的面板，获取对应的参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      );
      // 失败
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数失败");
      }
      // 成功
      this.$message.success(res.meta.msg);
      console.log(res.data);

      // 字符串转换为数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
        
        // 控制文本框的显示和隐藏
        item.inputVisible = false
        // 文本框中输入的值
        item.inputValue =''
     });

      // 分类赋值
      if (this.activeName === "many") {
        this.manyTableData = res.data;
      } else {
        this.onlyTableData = res.data;
      }
    },
    // 表单的关闭事件
    addDialogclose() {
      // 清空表单
      this.$refs.addFromRef.resetFields();
    },
    // 点击按钮添加参数
    addparams() {
      this.$refs.addFromRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addFrom.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加失败");
        }
        this.$message.success("添加成功");
        // 关闭对话框
        this.AddDialogVisible = false;
        // 重新获取列表数据
        this.getCateList();
      });
    },
    // 点击按钮修改参数
    async showEditDialog(attr_id) {
      // 发起请求获取需要修改的数据参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${attr_id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("获取参数数据失败");
      }
      //   成功
      this.editFrom = res.data;
      this.editDialogVisible = true;
    },
    // 取消修改的事件
    editDialogclose() {
      this.$refs.editFromRef.resetFields();
    },
    //   点击确定的事件
    editparams() {
      this.$refs.editFromRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editFrom.attr_id}`,
          {
            attr_name: this.editFrom.attr_name,
            attr_sel: this.activeName,
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改参数失败");
        }
        this.$message.success("修改参数成功");
        // 重新渲染
        this.getParamsData();
        // 关闭对话框
        this.editDialogVisible = false;
      });
    },
    // 根据id删除对应的参数项
    async removeParams(attr_id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);

      // 用户取消了删除
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      console.log("确认了删除");
      // 删除的业务逻辑

      const { data: res } = await this.$http.delete(
        `categories/${this.cateId}/attributes/${attr_id}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除失败");
      }
      this.$message.success("删除成功");
      // 重新渲染页面
      this.getParamsData();
    },
    // 文本框失去焦点，或按下了enter 都会触发
    async handleInputConfirm(row) {
      
      console.log('ok');
      // 优化判断它里面式空值嘛
      if(row.inputValue.trim().length === 0) {
        // 清空输入框
        row.inputValue = ''
        // 关闭输入框
        row.inputVisible = false
        return
      }
      // 如果没有return  则证明输入得内容需要有序处理
      // 添加到tag中 进行trim方法
      row.attr_vals.push(row.inputValue.trim()) 

        row.inputValue = ''
        row.inputVisible = false
        // 需要发起请求，保存这次操作
        // const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
        //   attr_name:row.attr_name,
        //   attr_sel:row.attr_sel,
        //   // 转换字符串
        //   attr_vals:row.attr_vals.join(' ')
        // })
        // if(res.meta.status !== 200) {
        //   return this.$message.error(res.meta.msg)
        // }
        // this.$message.success('添加参数成功')
        // // 重新渲染页面
        // this.getParamsData()
        this.saveAttrVals(row)
    },
    // 放入到数据库
    async saveAttrVals(row) {
        const {data:res} = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
          attr_name:row.attr_name,
          attr_sel:row.attr_sel,
          // 转换字符串
          attr_vals:row.attr_vals.join(' ')
        })
        if(res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('添加参数成功')
        
    },
    // 点击按钮，展示文本框
    showInput(row) {
      row.inputVisible = true
      // 让文本框自动获得焦点
      // $nextTick 方法得作用，就是当页面元素被重新渲染之后，才会指定回调函数中得代码
      this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
    },
    // 删除对应得参数和选项
    handleClose(i,row) {
      row.attr_vals.splice(i,1)

      this.saveAttrVals(row)
    },

  },
  // 计算属性
  computed: {
    // 如果按钮需要被禁用，则返回true，否则返回fasle
    isBtnDisabled() {
      if (this.selectedKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 当前选中的三级分类的id
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2];
      }
    },
    // 动态计算标题文本
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
};
</script>

<style scoped lang="less">
.cat_out {
  margin-top: 15px;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
